package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import model.College;
import model.Major;
import model.Student;
import util.DBHelper;
//学院业务控制类
public class CollegeServlet extends BaseServlet {

	//进入学生管理，查询所有学院
	public void selectAllCollege(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		College c = new College();
		c.getParams(req);
		//计算总行数
		String totalCountSql = c.getTotalCountSql();
		long totalCount = (long)DBHelper.query(totalCountSql).get(0);
		String sql = c.getSelectSql();
		//计算分页起始行
		int limitPageNo = (c.getPageNo() - 1) * c.getRowCount();
		sql += " limit " + limitPageNo + "," + c.getRowCount();
		List<College> list = DBHelper.query(sql, College.class, null);
		
		req.setAttribute("list", list);
		//添加分页参数
		req.setAttribute("pageNo", c.getPageNo());
		//计算总页数
		int totalPage = (int)(totalCount / c.getRowCount());
		if (totalCount % c.getRowCount() != 0 ) {
			totalPage += 1;
		}
		req.setAttribute("totalPage", totalPage);
		req.getRequestDispatcher("coll_mana.jsp").forward(req, res);
	}
	//添加学院
	public void addOneCollege(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		College c = new College();
		c.getParams(req);
		//组装sql
		String sql = c.getInsertSql();
		System.out.println(sql);
		int count = DBHelper.execute(sql, null);
		
		PrintWriter out = res.getWriter();
		if (count > 0) {
			out.write("1");
		}else {
			out.write("0");
		}
		out.flush();
		out.close();
	}
	//跳转更新学院页面
	public void updateCollegePage(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		College c = new College();
		c.getParams(req);
		
		//组装sql
		String sql = c.getSelectSql();
//		System.out.println(sql);
		List<College> list = DBHelper.query(sql, College.class, null);
//		System.out.println(list);
		req.setAttribute("obj", list.get(0));

		req.getRequestDispatcher("update_coll.jsp").forward(req, res);
	}
	//更新学院信息
	public void updataCollege(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		College c = new College();
		c.getParams(req);
		//组装sql
		String sql = c.getUpdateSql();

//		System.out.println(sql);
		int count1 = DBHelper.execute(sql, null);
		
		PrintWriter out = res.getWriter();
		if (count1 > 0) {
			out.write("1");
		}else {
			out.write("0");
		}
		out.flush();
		out.close();
	}

}
